<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noodp"/><title>Python实现图像全景拼接 | Yasin&#39;s Blog</title><meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content=""/>
<meta name="twitter:title" content="Python实现图像全景拼接"/>
<meta name="twitter:description" content=""/><meta name="twitter:creator" content="@wangyuexin8"/><meta name="Description" content="KEEP KWARKING"><meta property="og:title" content="Python实现图像全景拼接" />
<meta property="og:description" content="目标：将数张有重叠部分的图像通过特征点检测，匹配，图像变换拼成一幅无缝的全景图或高分辨率图像 在图像拼接中首先利用SIFT算法提取图像特征进而" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://blog.aimoon.top/panorama/" /><meta property="og:image" content="https://blog.aimoon.top/images/favicon.svg"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2020-08-09T11:06:26&#43;08:00" />
<meta property="article:modified_time" content="2021-03-29T11:34:14&#43;08:00" /><meta property="og:site_name" content="Yasin&#39;s Blog" />

<meta name="application-name" content="YASIN">
<meta name="apple-mobile-web-app-title" content="YASIN"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="icon" href="/images/favicon.svg" type="image/x-icon"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://blog.aimoon.top/panorama/" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Python实现图像全景拼接",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/blog.aimoon.top\/panorama\/"
        },"image": ["https:\/\/blog.aimoon.top\/images\/cover.png"],"genre": "posts","keywords": "实战, OpenCV, SIFT, RANSAC","wordCount":  1236 ,
        "url": "https:\/\/blog.aimoon.top\/panorama\/","datePublished": "2020-08-09T11:06:26+08:00","dateModified": "2021-03-29T11:34:14+08:00",
        "publisher": {
            "@type": "Person",
            "name": "Wang Yuexin", "image": [
            {
            "@type": "ImageObject",
            "url": "https:\/\/blog.aimoon.top\/images\/avatars.png"
            }
            ]},"author": {
                "@type": "Person",
                "name": "Wang Yuexin"
            },"description": ""
    }
    </script><script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        "itemListElement": [{
            "@type": "ListItem",
            "position": 1,
            "name": "主页",
            "item": "https:\/\/blog.aimoon.top"
        },{
            "@type": "ListItem",
            "position": 2,
            "name": "计算机视觉",
            "item": "https://blog.aimoon.top/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%A7%86%E8%A7%89/"
        },{
                "@type": "ListItem",
                "position": 3,
                "name": "Python实现图像全景拼接"
            }]
    }
</script></head>
    <body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('light' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'light' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header>
    <div class="desktop header" id="header-desktop">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="Yasin&#39;s Blog" class="header-logo logo-svg">Yasin&#39;s Blog</a>
            </div>
            <div class="menu">
                <nav>
                    <h2 class="display-hidden">Основная навигация</h2>
                    <ul class="menu-inner"><li>
                            <a class="menu-item" href="/posts/"> 目录 </a>
                        </li><li>
                            <a class="menu-item" href="/tags/"> 标签 </a>
                        </li><li>
                            <a class="menu-item" href="/categories/"> 归档 </a>
                        </li><li>
                            <a class="menu-item" href="/comments/"> 留言 </a>
                        </li><li>
                            <a class="menu-item" href="https://aimoon.top" rel="noopener noreffer" target="_blank"> 主页 </a>
                        </li></ul>
                </nav><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="search……" id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <span class="svg-icon icon-search"></span>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <span class="svg-icon icon-cancel"></span>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <span class="svg-icon icon-loading"></span>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                <span class="svg-icon icon-moon"></span>
                </a>
            </div>
        </div>
    </div><div class="mobile header" id="header-mobile">
        <div class="header-container">
            <div class="header-wrapper">
                <div class="header-title">
                    <a href="/" title="Yasin&#39;s Blog" class="header-logo">Yasin&#39;s Blog</a>
                </div>
                <div class="menu-toggle" id="menu-toggle-mobile">
                    <span></span><span></span><span></span>
                </div>
            </div>
            <div class="menu" id="menu-mobile"><div class="search-wrapper">
                        <div class="search mobile" id="search-mobile">
                            <input type="text" placeholder="search……" id="search-input-mobile">
                            <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                                <span class="svg-icon icon-search"></span>
                            </a>
                            <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="清空">
                                <span class="svg-icon icon-cancel"></span>
                            </a>
                            <span class="search-button search-loading" id="search-loading-mobile">
                                <span class="svg-icon icon-loading"></span>
                            </span>
                        </div>
                        <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                            取消
                        </a>
                    </div><nav>
                    <h2 class="display-hidden">Основная навигация</h2>
                    <ul><li>
                            <a class="menu-item" href="/posts/" title="">目录</a>
                        </li><li>
                            <a class="menu-item" href="/tags/" title="">标签</a>
                        </li><li>
                            <a class="menu-item" href="/categories/" title="">归档</a>
                        </li><li>
                            <a class="menu-item" href="/comments/" title="">留言</a>
                        </li><li>
                            <a class="menu-item" href="https://aimoon.top" title="" rel="noopener noreffer" target="_blank">主页</a>
                        </li></ul>
                </nav>
                <a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <span class="svg-icon icon-moon"></span>
                </a></div>
        </div>
    </div><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div></header><main class="main">
<div class="container content-article page-toc theme-classic"><div class="toc" id="toc-auto">
            <div class="toc-title">目录</div>
            <div class="toc-content" id="toc-content-auto"></div>
        </div>
    

    
    
    <article>
    

        <header class="header-post">

            

            
            <div class="post-title">

                    <div class="post-all-meta">
                        <nav class="breadcrumbs">
    <ol>
        <li><a href="/">主页 </a></li><li><a href="/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%A7%86%E8%A7%89/">计算机视觉 </a></li><li>Python实现图像全景拼接</li>
    </ol>
</nav>
                        <h1 class="single-title flipInX">Python实现图像全景拼接</h1><div class="post-meta summary-post-meta"><span class="post-category meta-item">
                                <a href="/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%A7%86%E8%A7%89/"><span class="svg-icon icon-folder"></span>计算机视觉</a>
                            </span><span class="post-meta-date meta-item">
                                <span class="svg-icon icon-clock"></span><time class="timeago" datetime="2020-08-09">2020-08-09</time>
                            </span><span class="post-meta-words meta-item">
                                <span class="svg-icon icon-pencil"></span>约 1236 字
                            </span>
                            <span class="post-meta-reading meta-item">
                                <span class="svg-icon icon-stopwatch"></span>预计阅读 3 分钟
                            </span>
                        </div>

                    </div>

                </div>

                </header>

        <div class="article-post toc-start">

            <div class="content-block content-block-first content-block-position">

                <div class="post single"><div class="image-theme-classic">
                        <img src="https://img-blog.csdnimg.cn/20200809110956387.png" style="width: 100%">
                    </div><div class="details toc" id="toc-static"  data-kept="">
                        <div class="details-summary toc-title">
                            <span>目录</span>
                        </div>
                        <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents"></nav></div>
                    </div><p><strong>目标</strong>：将数张有重叠部分的图像通过特征点检测，匹配，图像变换拼成一幅无缝的全景图或高分辨率图像</p>
<p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200809110424857.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200809110424857.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p>在图像拼接中首先利用SIFT算法提取图像特征进而进行特征匹配，继而使用RANSAC算法对特征匹配的结果进行优化，接着利用图像变换结构进行图像映射，最终进行图像融合。</p>
<p>在图像拼接过程中，运用SIFT局部描述算子检测图像中的关键点和特征，SIFT特征是基于物体上的一些局部外观的兴趣点而与影像的大小和旋转无关。对于光线、噪声、些微视角改变的容忍度也相当高，所以用来检测要拼接图像的特征及关键点就很有优势。而接下来即步骤三是找到重叠的图片部分，连接所有图片之后就可以形成一个基本的全景图了。匹配图片最常用的方式是采用RANSAC（RANdom SAmple Consensus, 随机抽样一致），用此排除掉不符合大部分几何变换的匹配。之后利用这些匹配的点来估算单应矩阵”（Homography Estimation），也就是将其中一张图像通过关联性和另一张匹配。</p>
<p><strong>使用的算法</strong>：</p>
<ul>
<li><a href="https://blog.aimoon.top/2020/07/fitting/#roubst-fitting--ransac" target="_blank" rel="noopener noreffer">RANSAC</a></li>
<li><a href="https://blog.aimoon.top/2020/07/edgedetection2/#sift%E7%89%B9%E5%BE%81" target="_blank" rel="noopener noreffer">SIFT</a></li>
</ul>
<p><strong>1. 利用SIFT方法检测特征点</strong></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python">    <span class="k">def</span> <span class="nf">detectAndDescribe</span><span class="p">(</span><span class="n">image</span><span class="p">):</span>
        <span class="c1"># 将彩色图片转换成灰度图</span>
        <span class="n">gray</span> <span class="o">=</span> <span class="n">cv2</span><span class="o">.</span><span class="n">cvtColor</span><span class="p">(</span><span class="n">image</span><span class="p">,</span> <span class="n">cv2</span><span class="o">.</span><span class="n">COLOR_BGR2GRAY</span><span class="p">)</span>

        <span class="c1"># 建立SIFT生成器</span>
        <span class="n">descriptor</span> <span class="o">=</span> <span class="n">cv2</span><span class="o">.</span><span class="n">xfeatures2d</span><span class="o">.</span><span class="n">SIFT_create</span><span class="p">()</span>
        <span class="c1"># 检测SIFT特征点，并计算描述子</span>
        <span class="p">(</span><span class="n">kps</span><span class="p">,</span> <span class="n">features</span><span class="p">)</span> <span class="o">=</span> <span class="n">descriptor</span><span class="o">.</span><span class="n">detectAndCompute</span><span class="p">(</span><span class="n">image</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span>

        <span class="c1"># 将结果转换成NumPy数组</span>
        <span class="n">kps</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">float32</span><span class="p">([</span><span class="n">kp</span><span class="o">.</span><span class="n">pt</span> <span class="k">for</span> <span class="n">kp</span> <span class="ow">in</span> <span class="n">kps</span><span class="p">])</span>

        <span class="c1"># 返回特征点集，及对应的描述特征</span>
        <span class="k">return</span> <span class="p">(</span><span class="n">kps</span><span class="p">,</span> <span class="n">features</span><span class="p">)</span>
</code></pre></td></tr></table>
</div>
</div><p><strong>2. 将检测到的特征点进行匹配</strong></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python">    <span class="k">def</span> <span class="nf">matchKeypoints</span><span class="p">(</span><span class="n">kpsA</span><span class="p">,</span> <span class="n">kpsB</span><span class="p">,</span> <span class="n">featuresA</span><span class="p">,</span> <span class="n">featuresB</span><span class="p">,</span> <span class="n">ratio</span><span class="p">,</span> <span class="n">reprojThresh</span><span class="p">):</span>
        <span class="c1"># 建立暴力匹配器</span>
        <span class="n">matcher</span> <span class="o">=</span> <span class="n">cv2</span><span class="o">.</span><span class="n">BFMatcher</span><span class="p">()</span>
  
        <span class="c1"># 使用KNN检测来自A、B图的SIFT特征匹配对，K=2</span>
        <span class="n">rawMatches</span> <span class="o">=</span> <span class="n">matcher</span><span class="o">.</span><span class="n">knnMatch</span><span class="p">(</span><span class="n">featuresA</span><span class="p">,</span> <span class="n">featuresB</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>

        <span class="n">matches</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">rawMatches</span><span class="p">:</span>
            <span class="c1"># 当最近距离跟次近距离的比值小于ratio值时，保留此匹配对</span>
            <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">m</span><span class="p">)</span> <span class="o">==</span> <span class="mi">2</span> <span class="ow">and</span> <span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">distance</span> <span class="o">&lt;</span> <span class="n">m</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">distance</span> <span class="o">*</span> <span class="n">ratio</span><span class="p">:</span>
            <span class="c1"># 存储两个点在featuresA, featuresB中的索引值</span>
                <span class="n">matches</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">trainIdx</span><span class="p">,</span> <span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">queryIdx</span><span class="p">))</span>

        <span class="c1"># 当筛选后的匹配对大于4时，计算视角变换矩阵</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">matches</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">4</span><span class="p">:</span>
            <span class="c1"># 获取匹配对的点坐标</span>
            <span class="n">ptsA</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">float32</span><span class="p">([</span><span class="n">kpsA</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="p">(</span><span class="n">_</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span> <span class="ow">in</span> <span class="n">matches</span><span class="p">])</span>
            <span class="n">ptsB</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">float32</span><span class="p">([</span><span class="n">kpsB</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">_</span><span class="p">)</span> <span class="ow">in</span> <span class="n">matches</span><span class="p">])</span>

            <span class="c1"># 计算视角变换矩阵</span>
            <span class="p">(</span><span class="n">H</span><span class="p">,</span> <span class="n">status</span><span class="p">)</span> <span class="o">=</span> <span class="n">cv2</span><span class="o">.</span><span class="n">findHomography</span><span class="p">(</span><span class="n">ptsA</span><span class="p">,</span> <span class="n">ptsB</span><span class="p">,</span> <span class="n">cv2</span><span class="o">.</span><span class="n">RANSAC</span><span class="p">,</span> <span class="n">reprojThresh</span><span class="p">)</span>

            <span class="c1"># 返回结果</span>
            <span class="k">return</span> <span class="p">(</span><span class="n">matches</span><span class="p">,</span> <span class="n">H</span><span class="p">,</span> <span class="n">status</span><span class="p">)</span>

        <span class="c1"># 如果匹配对小于4时，返回None</span>
        <span class="k">return</span> <span class="bp">None</span>
</code></pre></td></tr></table>
</div>
</div><p><strong>3. 将匹配的特征点可视化</strong></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python">    <span class="k">def</span> <span class="nf">drawMatches</span><span class="p">(</span><span class="n">imageA</span><span class="p">,</span> <span class="n">imageB</span><span class="p">,</span> <span class="n">kpsA</span><span class="p">,</span> <span class="n">kpsB</span><span class="p">,</span> <span class="n">matches</span><span class="p">,</span> <span class="n">status</span><span class="p">):</span>
        <span class="c1"># 初始化可视化图片，将A、B图左右连接到一起</span>
        <span class="p">(</span><span class="n">hA</span><span class="p">,</span> <span class="n">wA</span><span class="p">)</span> <span class="o">=</span> <span class="n">imageA</span><span class="o">.</span><span class="n">shape</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span>
        <span class="p">(</span><span class="n">hB</span><span class="p">,</span> <span class="n">wB</span><span class="p">)</span> <span class="o">=</span> <span class="n">imageB</span><span class="o">.</span><span class="n">shape</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span>
        <span class="n">vis</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">((</span><span class="nb">max</span><span class="p">(</span><span class="n">hA</span><span class="p">,</span> <span class="n">hB</span><span class="p">),</span> <span class="n">wA</span> <span class="o">+</span> <span class="n">wB</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">dtype</span><span class="o">=</span><span class="s2">&#34;uint8&#34;</span><span class="p">)</span>
        <span class="n">vis</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="n">hA</span><span class="p">,</span> <span class="mi">0</span><span class="p">:</span><span class="n">wA</span><span class="p">]</span> <span class="o">=</span> <span class="n">imageA</span>
        <span class="n">vis</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="n">hB</span><span class="p">,</span> <span class="n">wA</span><span class="p">:]</span> <span class="o">=</span> <span class="n">imageB</span>

        <span class="c1"># 联合遍历，画出匹配对</span>
        <span class="k">for</span> <span class="p">((</span><span class="n">trainIdx</span><span class="p">,</span> <span class="n">queryIdx</span><span class="p">),</span> <span class="n">s</span><span class="p">)</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">matches</span><span class="p">,</span> <span class="n">status</span><span class="p">):</span>
            <span class="c1"># 当点对匹配成功时，画到可视化图上</span>
            <span class="k">if</span> <span class="n">s</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
                <span class="c1"># 画出匹配对</span>
                <span class="n">ptA</span> <span class="o">=</span> <span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">kpsA</span><span class="p">[</span><span class="n">queryIdx</span><span class="p">][</span><span class="mi">0</span><span class="p">]),</span> <span class="nb">int</span><span class="p">(</span><span class="n">kpsA</span><span class="p">[</span><span class="n">queryIdx</span><span class="p">][</span><span class="mi">1</span><span class="p">]))</span>
                <span class="n">ptB</span> <span class="o">=</span> <span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">kpsB</span><span class="p">[</span><span class="n">trainIdx</span><span class="p">][</span><span class="mi">0</span><span class="p">])</span> <span class="o">+</span> <span class="n">wA</span><span class="p">,</span> <span class="nb">int</span><span class="p">(</span><span class="n">kpsB</span><span class="p">[</span><span class="n">trainIdx</span><span class="p">][</span><span class="mi">1</span><span class="p">]))</span>
                <span class="n">cv2</span><span class="o">.</span><span class="n">line</span><span class="p">(</span><span class="n">vis</span><span class="p">,</span> <span class="n">ptA</span><span class="p">,</span> <span class="n">ptB</span><span class="p">,</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">),</span> <span class="mi">1</span><span class="p">)</span>

        <span class="c1"># 返回可视化结果</span>
        <span class="k">return</span> <span class="n">vis</span>
</code></pre></td></tr></table>
</div>
</div><p>




<figure class="render-image"><a target="_blank" href="https://img-blog.csdnimg.cn/20200809110512171.png" title=" " >
        <img loading="lazy" decoding="async"
             class="render-image"
             src="https://img-blog.csdnimg.cn/20200809110512171.png"
            alt=" "
        />
    </a><figcaption class="image-caption"> </figcaption>
</figure></p>
<p><strong>4. 图像拼接</strong></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python">    <span class="k">def</span> <span class="nf">stitch</span><span class="p">(</span><span class="n">images</span><span class="p">,</span> <span class="n">ratio</span><span class="o">=</span><span class="mf">0.75</span><span class="p">,</span> <span class="n">reprojThresh</span><span class="o">=</span><span class="mf">4.0</span><span class="p">,</span><span class="n">showMatches</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span>
        <span class="c1">#获取输入图片</span>
        <span class="p">(</span><span class="n">imageB</span><span class="p">,</span> <span class="n">imageA</span><span class="p">)</span> <span class="o">=</span> <span class="n">images</span>
        <span class="c1">#检测A、B图片的SIFT关键特征点，并计算特征描述子</span>
        <span class="p">(</span><span class="n">kpsA</span><span class="p">,</span> <span class="n">featuresA</span><span class="p">)</span> <span class="o">=</span> <span class="n">detectAndDescribe</span><span class="p">(</span><span class="n">imageA</span><span class="p">)</span>
        <span class="p">(</span><span class="n">kpsB</span><span class="p">,</span> <span class="n">featuresB</span><span class="p">)</span> <span class="o">=</span> <span class="n">detectAndDescribe</span><span class="p">(</span><span class="n">imageB</span><span class="p">)</span>

        <span class="c1"># 匹配两张图片的所有特征点，返回匹配结果</span>
        <span class="n">M</span> <span class="o">=</span> <span class="n">matchKeypoints</span><span class="p">(</span><span class="n">kpsA</span><span class="p">,</span> <span class="n">kpsB</span><span class="p">,</span> <span class="n">featuresA</span><span class="p">,</span> <span class="n">featuresB</span><span class="p">,</span> <span class="n">ratio</span><span class="p">,</span> <span class="n">reprojThresh</span><span class="p">)</span>

        <span class="c1"># 如果返回结果为空，没有匹配成功的特征点，退出算法</span>
        <span class="k">if</span> <span class="n">M</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">None</span>

        <span class="c1"># 否则，提取匹配结果</span>
        <span class="c1"># H是3x3视角变换矩阵      </span>
        <span class="p">(</span><span class="n">matches</span><span class="p">,</span> <span class="n">H</span><span class="p">,</span> <span class="n">status</span><span class="p">)</span> <span class="o">=</span> <span class="n">M</span>
        <span class="c1"># 将图片A进行视角变换，result是变换后图片</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">cv2</span><span class="o">.</span><span class="n">warpPerspective</span><span class="p">(</span><span class="n">imageA</span><span class="p">,</span> <span class="n">H</span><span class="p">,</span> <span class="p">(</span><span class="n">imageA</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">imageB</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">imageA</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]))</span>
        <span class="n">cv_show</span><span class="p">(</span><span class="s1">&#39;result&#39;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
        <span class="c1"># 将图片B传入result图片最左端</span>
        <span class="n">result</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="n">imageB</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="mi">0</span><span class="p">:</span><span class="n">imageB</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]]</span> <span class="o">=</span> <span class="n">imageB</span>
        <span class="n">cv_show</span><span class="p">(</span><span class="s1">&#39;result&#39;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
        <span class="c1"># 检测是否需要显示图片匹配</span>
        <span class="k">if</span> <span class="n">showMatches</span><span class="p">:</span>
            <span class="c1"># 生成匹配图片</span>
            <span class="n">vis</span> <span class="o">=</span> <span class="n">drawMatches</span><span class="p">(</span><span class="n">imageA</span><span class="p">,</span> <span class="n">imageB</span><span class="p">,</span> <span class="n">kpsA</span><span class="p">,</span> <span class="n">kpsB</span><span class="p">,</span> <span class="n">matches</span><span class="p">,</span> <span class="n">status</span><span class="p">)</span>
            <span class="c1"># 返回结果</span>
            <span class="k">return</span> <span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">vis</span><span class="p">)</span>

        <span class="c1"># 返回匹配结果</span>
        <span class="k">return</span> <span class="n">result</span>
</code></pre></td></tr></table>
</div>
</div></div><footer>
                        <div class="post">


<div class="post-share"><div class="share-link">
        <a class="share-icon share-twitter" href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://blog.aimoon.top/panorama/" data-title="Python实现图像全景拼接" data-via="wangyuexin8" data-hashtags="实战,OpenCV,SIFT,RANSAC"><span class="svg-social-icon icon-twitter"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-facebook" href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://blog.aimoon.top/panorama/" data-hashtag="实战"><span class="svg-social-icon icon-facebook"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-whatsapp" href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://blog.aimoon.top/panorama/" data-title="Python实现图像全景拼接" data-web><span class="svg-social-icon icon-whatsapp"></span></a>
    </div><div class="share-link">
        <a class="share-icon share-blogger" href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://blog.aimoon.top/panorama/" data-title="Python实现图像全景拼接" data-description=""><span class="svg-social-icon icon-blogger"></span></a>
    </div></div>

<div class="footer-post-author">
    <div class="author-avatar"><a href="https://aimoon.top" target="_blank"><img alt="Undergraduate Student of Artificial Intelligence 😜" src="https://blog.aimoon.top/images/avatars.png"></a></div>
    <div class="author-info">
        <div class="name"><a href="https://aimoon.top" target="_blank">Wang Yuexin</a></div>
        <div class="number-posts">Undergraduate Student of Artificial Intelligence 😜</span></div>
    </div>
</div><div class="post-tags"><a href="/tags/%E5%AE%9E%E6%88%98/" class="tag">实战</a><a href="/tags/opencv/" class="tag">OpenCV</a><a href="/tags/sift/" class="tag">SIFT</a><a href="/tags/ransac/" class="tag">RANSAC</a></div></div>
                </footer></div>
        <div id="toc-final"></div>
        </div>

    
    </article>
    <section class="page single comments content-block-position">
        <h1 class="display-hidden">Комментарии</h1><div id="comments"><div id="disqus_thread" class="comment" style="padding-top: 1.5rem"></div>
            <noscript>
                Please enable JavaScript to view the comments powered by <a href="https://disqus.com/?ref_noscript">Disqus</a>.
            </noscript></div></section></div>

</main><footer class="footer">
        <div class="footer-container"><div class="footer-line"><div><span id="timeDate">正在烧脑计算建站时间...</span><span id="times"></span><script>var now = new Date();function createtime(){var grt= new Date("05/20/2020 00:00:00");now.setTime(now.getTime()+250);days = (now - grt ) / 1000 / 60 / 60 / 24;dnum = Math.floor(days);hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);hnum = Math.floor(hours);if(String(hnum).length ==1 ){hnum = "0" + hnum; }minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);mnum = Math.floor(minutes);if(String(mnum).length ==1 ){mnum = "0" + mnum;}seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);snum = Math.round(seconds);if(String(snum).length ==1 ){snum = "0" + snum;}document.getElementById("timeDate").innerHTML = "&nbsp"+dnum+"&nbsp天";document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";}setInterval("createtime()",250);</script></div></div><div class="footer-line"><i class="svg-icon icon-copyright"></i><span>2020 - 2021</span><span class="author">&nbsp;<a href="https://aimoon.top" target="_blank">Yasin</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span><span class="icp-splitter">&nbsp;|&nbsp;</span><br class="icp-br"/>
                    <span class="icp"><a href="https://blog.pangao.vip/icp/xmoon.info">🧑ICP证000000号</a></span></div>
        </div>
    </footer></div>

        <aside id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="svg-icon icon-arrow-up"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="svg-icon icon-comments-fixed"></i>
            </a>
        </aside><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/copy-tex.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.css"><script src="https://yasin5.disqus.com/embed.js" defer></script><script src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js"></script><script src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.37.1/dist/autocomplete.min.js"></script><script src="https://cdn.jsdelivr.net/npm/lunr@2.3.8/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="https://cdn.jsdelivr.net/npm/twemoji@13.0.0/dist/twemoji.min.js"></script><script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script><script src="https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/copy-tex.min.js"></script><script src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/mhchem.min.js"></script><script src="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":-1},"comment":{},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验."},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":30,"type":"lunr"},"twemoji":true};</script><script src="/js/theme.min.js"></script><script>
                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

	        ga('create', 'UA-167439955-2', 'auto');
	        ga('set', 'anonymizeIp', true);
	        ga('send', 'pageview');
	    </script></body>
</html>
